package record

import (
	"gin/common/lib/gorm"
	"gin/dao/entity"
	"gin/model/body"
)

// Add 添加运动记录
func Add(p body.AddRecordParam) {
	gorm.GinDb.SubTable("cmf_users_exercise_record", p.Uid).Create(&p)
}

// Complete 完成任务
func Complete(uid int64, p body.CompleteRecordParam) {
	gorm.GinDb.SubTable("cmf_users_exercise_record", uid).Where("id = ?", p.Id).Updates(&p)
}

// Detail 运动详情
func Detail(uid, id int64) entity.Record {
	info := entity.Record{}
	gorm.GinDb.SubTable("cmf_users_exercise_record", uid).Where("id = ?", id).Limit(1).Find(&info)
	return info
}

// List 运动记录
func List(p body.RecordListParam) ([]*entity.RecordDetail, int64) {
	list := make([]*entity.RecordDetail, 0)
	tableName := gorm.SubTable(gorm.GinDb, "cmf_users_exercise_record", p.Uid)
	db := gorm.GinDb.Table(tableName+" as r").Select("r.*,e.name as exercise_name,e.img_url as exercise_img_url").Where("exercise_status = 3 and r.uid = ?", p.Uid)
	db.Joins("left join cmf_exercise e on r.exercise_id = e.id")
	if p.ExerciseId > 0 {
		db.Where("exercise_id = ?", p.ExerciseId)
	}
	db.Order("id desc").Find(&list)
	return list, ListCount(p)
}

// ListCount 运动记录条数
func ListCount(p body.RecordListParam) int64 {
	var count int64
	db := gorm.GinDb.SubTable("cmf_users_exercise_record", p.Uid)
	db.Where("exercise_status = 3 and r.uid = ?", p.Uid)
	if p.ExerciseId > 0 {
		db.Where("exercise_id = ?", p.ExerciseId)
	}
	db.Count(&count)
	return count
}

// Del 删除运动记录
func Del(uid, id int64) {
	gorm.GinDb.SubTable("cmf_users_exercise_record", uid).
		Where("id = ?", id).Delete(&entity.Record{})
}

// IsDoingCount 获取正在运动的记录
func IsDoingCount(uid int64) entity.Record {
	info := entity.Record{}
	gorm.GinDb.SubTable("cmf_users_exercise_record", uid).
		Where("uid= ? and exercise_status != 3", uid).Limit(1).Find(&info)
	return info
}

// GetNew 获取最新的记录
func GetNew(uid int64) entity.Record {
	info := entity.Record{}
	gorm.GinDb.SubTable("cmf_users_exercise_record", uid).
		Where("uid= ?", uid).Order("id desc").Limit(1).Find(&info)
	return info
}
